<template>
	<div>
		<use-table ref="tbl" :tableRefs="$refs.etbl"></use-table>
		<div class="container_status dflex_vertical_c">
			<div class="item_interval" v-for="(item, i) in stateDatas" :key="i">
				<el-button class="badge_txt" :class="{ active: item.name == state }" size="small" @click="cutSta(item)">
					{{ item.name }}
				</el-button>
				<v-countup class="badge" start-value="0" :end-value="item.cnt"></v-countup>
			</div>
		</div>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">商品名称：</div>
					<el-input v-model="req.name" placeholder="请输入" class="search_input" @change="search" clearable>
					</el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">分类：</div>
					<el-cascader class="search_input" v-model="req.cid" :show-all-levels="false" :options="classOptions"
						ref="cascaderObj" filterable
						:props="{ expandTrigger: 'hover', checkStrictly: true, emitPath: false, value: '_id', label: 'name' }"
						clearable @change="categoryChange">
						<template slot-scope="{ node, data }">
							<div @click="categoryChange(data._id)" class="cascader">{{data.name}}</div>
						</template>
					</el-cascader>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
				<div class="search_advanced margin_b_20" @click="advancedSearch = !advancedSearch"
					v-if="!advancedSearch">高级筛选</div>
				<div class="search_common margin_b_20" @click="advancedSearch = !advancedSearch" v-if="advancedSearch">
					常用筛选</div>
			</div>
		</div>
		<div class="container last_container use-table">
			<div class="dflex_sb margin_b_15 table-head">
				<div>
					<el-button class="batch-btn padding0" :loading="removesBtnLoading" @click="removes"
						v-if="state != '销售中'">删除<span v-if="selectDatas.length">×{{selectDatas.length}}</span>
					</el-button>
					<el-button class="batch-btn padding0" type="info" plain :loading="outsBtnLoading" @click="outs"
						v-if="state == '销售中'">下架<span v-if="selectDatas.length">×{{selectDatas.length}}</span>
					</el-button>
				</div>
				<div class="dflex_vertical_c  ">
					<div class="">限时抢购：</div>
					<el-input v-model="about.limit_title" placeholder="请输入" class="search_input" clearable>
					</el-input>
					<div class=" margin_l_10">新福利：</div>
					<el-input v-model="about.hot_title" placeholder="请输入" class="search_input" clearable>
					</el-input>
					<el-button class="add-btn pos_r padding0 margin_l_10" @click="updateAhout">保存</el-button>
				</div>
				<el-button class="add-btn pos_r padding0" icon="iconfont iconxinzeng" @click="toAdd">新增</el-button>
			</div>
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas"
				@selection-change="selectionChange" highlight-current-row>
				<el-table-column type="selection" :selectable="selectable"></el-table-column>
				<el-table-column label="排序" width="200" align="center">
					<template slot-scope="scope">
						<el-input-number size="small" :min="1" v-model="scope.row.sort"
							@change="(newSort, oldSort) => sortChange(newSort, oldSort, scope.row)"
							@blur="scope.row.sort = parseInt(scope.row.sort)"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column label="商品" width="330" align="center">
					<template slot-scope="scope">
						<div class="dflex_vertical_c">
							<use-carousel :width="84" :height="84" :imgs="scope.row.imgs" :video="scope.row.video">
							</use-carousel>
							<div class="left_just margin_l_10">
								<el-popover popper-class="use_popover" :open-delay="200" :close-delay="40"
									placement="right" :title="scope.row.name" trigger="hover"
									:content="scope.row.name_pw || '--'">
									<div slot="reference" class="dflex_d_c">
										<div class="ellipsis crpr">{{ scope.row.name }}</div>
										<div class="ellipsis crpr">{{ scope.row.name_pw || '--' }}</div>
									</div>
								</el-popover>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="ID" align="center">
					<template slot-scope="scope">
						{{scope.row._id}}
					</template>
				</el-table-column>
				<!-- <el-table-column label="VIP价" align="center">
					<template slot-scope="scope">
						<div class="price" v-if="scope.row.is_vip == '是' && scope.row.vip_price">
							{{ scope.row.vip_price / 100 }}
						</div>
						<div v-else>--</div>
					</template>
				</el-table-column> -->
				<el-table-column label="价格" align="center" width="140">
					<template slot-scope="scope">
						<div class="price">{{ scope.row.price / 100 }}</div>
						<div class="m_price">{{ scope.row.market_price / 100 }}</div>
					</template>
				</el-table-column>
				<el-table-column label="限时抢购" align="center">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" :content="scope.row.limited == 1 ? '取消限时抢购' : '启用限时抢购'"
							placement="top" :hide-after="1000" :enterable="false" effect="light">
							<el-switch v-model="scope.row.limited" active-color="#ff6a6c" inactive-color="#bbb"
								:active-value="1" :inactive-value="0" @change="limitedChang(scope.row)"></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column label="新福利" align="center">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" :content="scope.row.hot == 1 ? '取消新福利' : '启用新福利'" placement="top"
							:hide-after="1000" :enterable="false" effect="light">
							<el-switch v-model="scope.row.hot" active-color="#ff6a6c" inactive-color="#bbb"
								:active-value="1" :inactive-value="0" @change="hotChang(scope.row)"></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column label="数据统计" align="center" width="140">
					<template slot-scope="scope">
						<div class="left_just" style="margin-left: 32px;">
							<div>已售数:{{ scope.row.sale_cnt }}</div>
							<div>访问数:{{ scope.row.visit_cnt }}</div>
							<div>收藏数:{{ scope.row.collect_cnt }}</div>
							<div>分享数:{{ scope.row.share_cnt }}</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="标签" width="260" align="center">
					<template slot-scope="scope">
						<div class="left_just padding_l_40">
							<el-tag effect="plain" class="margin_t_5 margin_r_5 sele_none" type="info"
								v-for="(item, i) in scope.row.tags" :key="i">{{ item }}</el-tag>
						</div>
					</template>
				</el-table-column>
				<el-table-column property="state" label="状态" align="center"></el-table-column>
				<el-table-column label="操作" align="center" fixed="right" width="120">
					<template slot-scope="scope">
						<div>
							<el-tooltip :open-delay="350" content="上架" placement="top" :hide-after="1000"
								:enterable="false" effect="light"
								v-if="scope.row.state == '待审核' || scope.row.state == '已下架'">
								<el-button circle class="table-btn" size="medium" icon="el-icon-upload2"
									@click="staUp(scope.row._id)"></el-button>
							</el-tooltip>
							<el-tooltip :open-delay="350" content="下架" placement="top" :hide-after="1000"
								:enterable="false" effect="light" v-if="scope.row.state == '销售中'">
								<el-button circle class="table-btn" size="medium" icon="el-icon-download"
									@click="staOut(scope.row._id)"></el-button>
							</el-tooltip>
							<el-tooltip :open-delay="350" content="编辑" placement="top" :hide-after="1000"
								:enterable="false" effect="light">
								<el-button circle class="table-btn" size="medium" icon="el-icon-edit"
									@click="toEdit(scope.row._id)"></el-button>
							</el-tooltip>
						</div>
						<div class="margin_t_10">
							<!-- <el-tooltip :open-delay="350" content="预览" placement="top" :hide-after="1000"
								:enterable="false" effect="light"
								v-if="scope.row.state == '待审核' || scope.row.state == '销售中'">
								<el-button circle class="table-btn" size="medium" icon="el-icon-view"
									@click="preview(scope.row)"></el-button>
							</el-tooltip> -->
							<el-tooltip :open-delay="350" content="评价" placement="top" :hide-after="1000"
								:enterable="false" effect="light" v-if="scope.row.state == '销售中'">
								<el-button circle class="table-btn" size="medium" icon="el-icon-star-off"
									@click="toEvaluate(scope.row._id)"></el-button>
							</el-tooltip>
							<el-tooltip :open-delay="350" content="删除" placement="top" :hide-after="1000"
								:enterable="false" effect="light"
								v-if="scope.row.state == '待审核' || scope.row.state == '已下架'">
								<el-button circle class="table-btn" size="medium" icon="el-icon-delete"
									@click="remove(scope.row._id)"></el-button>
							</el-tooltip>
						</div>
					</template>
				</el-table-column>
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows"
				layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange"
				@current-change="currentChange"></el-pagination>
		</div>
		<el-drawer title="商品预览" size="500px" :visible.sync="previewDrawer" direction="rtl" :append-to-body="true">
			<div>
				<iphone v-show="btnType == 'iphone'" :url="iphoneUrl" @childCloseDialog="previewDrawer = false">
				</iphone>
				<iphonex v-show="btnType == 'iphonex'" :url="iphonexUrl"></iphonex>
				<div class="qrcode_box" v-show="btnType == 'qrCode'">
					<div class="dflex_vertical_c">
						<use-carousel :width="84" :height="84" :imgs="previewData.imgs" :video="previewData.video">
						</use-carousel>
						<div class="left_just margin_l_10">
							<el-popover popper-class="use_popover" :open-delay="200" :close-delay="40" placement="right"
								:title="previewData.name" trigger="hover" :content="previewData.name_pw || '--'">
								<div slot="reference" class="dflex_d_c">
									<div class="ellipsis crpr">{{ previewData.name }}</div>
									<div class="ellipsis crpr margin_t_5">{{ previewData.name_pw || '--' }}</div>
								</div>
							</el-popover>
						</div>
					</div>
					<div class="qrcode dflex_c margin_t_20 margin_b_30" ref="qrCodeUrl"></div>
					<div class="remark_txt center_just">扫一扫上面的二维码图案，预览商品</div>
				</div>
			</div>
			<div class="previewDrawerBtn pos_a">
				<el-button round :class="[btnType == 'iphone' ? 'active' : '']" class="table-btn"
					@click="previewDrawerBtn('iphone')">iphone</el-button>
				<el-button round :class="[btnType == 'iphonex' ? 'active' : '']" class="table-btn"
					@click="previewDrawerBtn('iphonex')">iphonex</el-button>
				<el-button round :class="[btnType == 'qrCode' ? 'active' : '']" class="table-btn"
					@click="previewDrawerBtn('qrCode')">二维码</el-button>
				<el-button round icon="el-icon-back" class="return-btn" @click="previewDrawer = false">返回</el-button>
			</div>
		</el-drawer>
	</div>
</template>

<script>
	import vCountup from 'vue-countupjs';
	import QRCode from 'qrcodejs2';
	const __name = 'wmzmall-goods';
	const __goodsCategory = 'wmzmall-goods-category';
	const __about = 'wmzmall-app-about';
	export default {
		components: {
			vCountup
		},
		data() {
			return {
				state: '全部',
				stateObj: {
					待审核: 0,
					销售中: 0,
					已下架: 0,
					全部: 0
				},
				stateDatas: [],
				advancedSearch: false,
				classOptions: [],
				req: {
					page: 1,
					rows: 10,
					orderby: 'sort asc',
					state: '',
					name: '',
					cid: 0
				},
				about: {
					limit_title: '限时抢购',
					hot_title: '新福利'
				},
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				tableTotal: 0,
				selectDatas: [],
				previewDrawer: false,
				previewData: {},
				previewId: '',
				btnType: 'iphone',
				iphoneUrl: '',
				iphonexUrl: '',
				searchBtnLoading: false,
				removesBtnLoading: false,
				outsBtnLoading: false,
				sortLastTime: null
			};
		},
		methods: {
			async loadAboutData() {
				await this.$db[__about]
					.totable()
					.then(res => {
						if (res.code == 200) {
							if( res.datas.rows[0]){
								this.about = res.datas.rows[0];
							}
						}
					});
			},
			async loadData(callback) {
				this.tableLoading = true;

				this.stateDatas = [];
				for (let key in this.stateObj) {
					this.stateDatas.push({
						name: key,
						cnt: this.stateObj[key]
					});
				}

				await this.$db[__name]
					.whereif(this.req.state && this.req.state != '全部', {
						state: this.req.state
					})
					.whereif(this.req.name, {
						name: new RegExp(this.$api.filterRegexpKey(this.req.name), 'i')
					})
					.whereif(this.req.cid, {
						cids: this.req.cid
					})
					.withgroup({
						field: 'state',
						obj: this.stateObj
					})
					.totable(this.req)
					.then(res => {
						if (res.code == 200) {
							if (res.datas.group && res.datas.group.datas) {
								this.stateDatas = res.datas.group.datas;
							}

							this.tableDatas = res.datas.rows;
							this.tableTotal = res.datas.total;

							if (typeof callback === 'function') {
								callback();
							}
						}
						this.searchBtnLoading = false;
						this.tableLoading = false;
					});
			},
			categoryChange(id) {
				this.req.cid = id || '';
				this.search();
				this.$refs.cascaderObj.dropDownVisible = false;
			},
			search() {
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			toAdd() {
				uni.navigateTo({
					url: `/pages/goods/list/goods_list_add_edit?tab=添加商品`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			staUp(id) {
				this.$confirm('此操作将上架此商品!', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$db[__name].update(id, {
						state: '销售中'
					}).then(res => {
						if (res.code == 200) this.loadData();
					});
				});
			},
			staOut(id) {
				this.$confirm('此操作将下架此商品!', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$db[__name].update(id, {
						state: '已下架'
					}).then(res => {
						if (res.code == 200) this.loadData();
					});
				});
			},
			toEdit(id) {
				uni.navigateTo({
					url: `/pages/goods/list/goods_list_add_edit?id=${id}&tab=编辑商品`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			toEvaluate(id) {
				uni.navigateTo({
					url: `/pages/goods/list/evaluate_add?id=${id}&tab=添加评价`
				});
			},
			preview(row) {
				this.previewData = row;
				this.previewId = row._id;
				this.previewDrawer = true;
				if (this.btnType == 'iphone') {
					this.btnType = 'iphone';
					this.iphoneUrl =
						`http://mall.wmeizi.com/#/sub-goods/pages/detail?id=${this.previewId}&admin=1`;
				} else if (this.btnType == 'iphonex') {
					this.btnType = 'iphonex';
					this.iphonexUrl =
						`http://mall.wmeizi.com/#/sub-goods/pages/detail?id=${this.previewId}&admin=1`;
				} else {
					this.btnType = 'qrCode';
					this.creatQrCode(`http://mall.wmeizi.com/#/sub-goods/pages/detail?id=${this.previewId}`);
				}
			},
			previewDrawerBtn(res) {
				if (res == 'iphone') {
					this.btnType = 'iphone';
					this.iphoneUrl =
						`http://mall.wmeizi.com/#/sub-goods/pages/detail?id=${this.previewId}&admin=1`;
				} else if (res == 'iphonex') {
					this.btnType = 'iphonex';
					this.iphonexUrl =
						`http://mall.wmeizi.com/#/sub-goods/pages/detail?id=${this.previewId}&admin=1`;
				} else {
					this.btnType = 'qrCode';
					this.creatQrCode(`http://mall.wmeizi.com/#/sub-goods/pages/detail?id=${this.previewId}`);
				}
			},
			creatQrCode(url) {
				this.$refs.qrCodeUrl.innerHTML = '';
				var qrcode = new QRCode(this.$refs.qrCodeUrl, {
					text: url, // 需要转换为二维码的内容
					width: 260,
					height: 260,
					colorDark: '#000000',
					colorLight: '#ffffff',
					correctLevel: QRCode.CorrectLevel.H
				});
			},
			remove(id) {
				this.$confirm('此操作将永久删除该数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$db[__name].remove(id).then(res => {
						if (res.code == 200) {
							this.loadData();
						}
					});
				});
			},
			selectionChange(datas) {
				this.selectDatas = datas;
			},
			selectable(datas) {
				if (this.state == '销售中') return true;

				if (datas.state == '销售中') {
					return false;
				}

				return true;
			},
			removes() {
				if (this.selectDatas.length <= 0) {
					this.$message('请勾选需要删除的数据');
					return;
				}

				let ids = this.selectDatas.map(x => x._id);

				this.$confirm('此操作将永久删除勾选数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.removesBtnLoading = true;
					this.$db[__name]
						.where({
							_id: this.$db.$cmd.in(ids)
						})
						.remove()
						.then(res => {
							if (res.code == 200) {
								this.loadData();
							}
							this.removesBtnLoading = false;
						}).catch(() => {
							this.removesBtnLoading = false;
						})
				});
			},
			outs() {
				if (this.selectDatas.length <= 0) {
					this.$message('请勾选需要下架的数据');
					return;
				}

				let ids = this.selectDatas.map(x => x._id);

				this.$confirm('此操作将下架勾选数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.outsBtnLoading = true;
					this.$db[__name]
						.where({
							_id: this.$db.$cmd.in(ids)
						})
						.update('', {
							state: '已下架'
						})
						.then(res => {
							if (res.code == 200) {
								this.outsBtnLoading = false;
								this.loadData();
							}
						}).catch(() => {
							this.outsBtnLoading = false;
						})
				});
			},
			sortChange(newSort, oldSort, row) {
				if (!newSort) {
					this.$nextTick(() => {
						row.sort = oldSort;
					})
					return;
				}

				if (event && ['change', 'mouseup'].includes(event.type)) {
					this.sortUpdate(row);
					return;
				}

				if (this.sortLastTime !== null) {
					clearTimeout(this.sortLastTime)
				}

				this.sortLastTime = setTimeout(() => {
					this.sortUpdate(row)
				}, 500);
			},
			sortUpdate(row) {
				this.$db[__name].update(row._id, {
					sort: parseInt(row.sort)
				}).catch(() => {
					this.loadData();
				})
			},
			limitedChang(row) {
				this.$db[__name].update(row._id, {
					limited: row.limited
				}).catch(() => {
					this.loadData();
				})
			},
			hotChang(row) {
				this.$db[__name].update(row._id, {
					hot: row.hot
				}).catch(() => {
					this.loadData();
				})
			},
			cutSta(item) {
				uni.setStorage({
					key: '__cutSta' + this.$route.path,
					data: item
				});

				this.state = item.name;
				this.req.state = item.name;
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			sizeChange(size) {
				this.$api.storagePaginationRows(size, this.$route.path);
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.req.rows = size;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			currentChange(current) {
				this.$api.storagePaginationPage(current, this.$route.path);
				this.req.page = current;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			setChildren(res) {
				res.forEach(item => {
					if (item.children && item.children.length <= 0) {
						item.children = null;
						return;
					}

					this.setChildren(item.children);
				});
			},
			updateAhout(row) {
				this.$db[__about].update(this.about._id, {
					limit_title: this.about.limit_title,
					hot_title: this.about.hot_title
				}).then(res => {
					if (res.code == 200) {
						this.$message('修改成功');
					}
				}).catch(() => {
					this.loadAboutData();
				})
			},
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
				if (this.req.cid) {
					this.advancedSearch = true;
				}
			}

			this.$db[__goodsCategory].where({
				state: "启用"
			}).totree({
				orderby: 'sort asc',
				startWith: 'pid == ""',
				loading: false
			}).then(res => {
				if (res.code == 200) {
					this.setChildren(res.datas);
					this.classOptions = res.datas;
				}
			});

			let thisCutSta = uni.getStorageSync('__cutSta' + this.$route.path);
			this.state = '全部';
			this.req.page = 1;
			this.req.state = this.state;
			if (thisCutSta) {
				this.state = thisCutSta.name;
				this.req.state = thisCutSta.name;
			}
			this.req.page = uni.getStorageSync('__paginationPage' + this.$route.path) || 1;
			this.req.rows = uni.getStorageSync('__paginationRows' + this.$route.path) || 10;
			this.loadAboutData()
			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style>
	.cascader {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		padding-left: 44px;
		z-index: 99;
	}

	.previewDrawerBtn {
		bottom: 20px;
		right: 20px;
	}

	.qrcode_box {
		margin: 16px;
		border-radius: 10px;
		padding: 20px;
		background-color: #fff;
		box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
	}

	.qrcode_box .ellipsis {
		max-width: 300px;
	}
</style>